<?php

namespace common\helpers\sms;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

/**
 * 签名助手 2017/11/19
 *
 * Class SignatureHelper
 */
class SignatureHelper
{

    const URL = "http://61.145.229.28:8806/MWGate/wmgw.asmx/MongateSendSubmit";
    const USER_ID = "XD0001";
    const PASSWORD = "688963";
    const PSZ_SUB_PORT = "0002";


    /**
     * @param $fromSystemType
     * @param $regionCode
     * @param $mobile
     * @param $templateId
     * @param $dataVariables
     * @return bool|mixed
     */
    public function request($mobile, $templateId, $dataVariables)
    {

        $msg = $this->format($dataVariables, $templateId);
        if (empty($msg)) {
            return true;
        }
        $data = [
            'userId' => self::USER_ID,
            'password' => self::PASSWORD,
            'pszMobis' => $mobile,
            'pszMsg' => $msg,
            'iMobiCount' => 1,
            'pszSubPort' => self::PSZ_SUB_PORT
        ];

        try {
            return $content = $this->fetchContent($data);
        } catch (RequestException $e) {
            return ($e->getMessage());
        } catch (\Exception $e) {
            return ($e->getMessage());
        }
    }

    private function fetchContent($data)
    {
        $client = new Client();
        try {
            $responses = $client->request(
                "GET",
                self::URL,
                [
                    'query' => $data
                ]
            );
            return json_decode(json_encode(simplexml_load_string($responses->getBody()->getContents())), true);
        } catch (RequestException $e) {
            throw  $e;
        } catch (\Exception $e) {
            throw  $e;
        }
    }

    private function format($dataVariables, $templateId)
    {
        $templateString = $this->getTemplate()[$templateId];
        foreach ($dataVariables as $key => $value) {
            $templateString = str_replace($value['Name'], $value['Value'], $templateString, $templateString);
        }
        return $templateString;
    }

    private function getTemplate()
    {
        return [
            '000012' => '客户您好，您的验证码是：#DV_CustomizedInfo#，5分钟以内有效。如非您本人操作，請拨打400-920-6600联系客服咨询，访问手机客户端及www.tthigo.com网站，或关注“tt海购”(微信服务号：tthgcom)，感谢您的关心与支持。',
            '000013' => '恭喜您在tt海购天天抽奖活动中获得#CARD_TYPE#,卡号#CARD_NO#，密码#PWD#，在结算页面中输入即可使用。（可与优惠券叠加)',
            "000014" => '这是你黑五的红包，内含现金礼卡CARD_MONEY元!现金礼卡卡号：CARD_NO 卡密：CARD_PWD  本卡为不记名礼品卡，不挂失， 不计息，不兑换现金。 可赠予他人，也可自己使用。礼卡有效期截止2018/11/11 23:59:59，有效期内可与优惠券码叠加使用，且每个订单可使用多张现金礼卡！
            --“盲选节”活动期内优惠多多，诚邀您持续关注~',
            '000015' =>'亲爱的用户，恭喜您拼团成功，您的拼团券是CARD_NO，雾霾天要好好保护自己~前往tt海购购买防护口罩吧！https://a.app.qq.com/o/simple.jsp?pkgname=com.newegg.higo&fromcase=40002',
        ];
    }
}